import React from 'react';
import { Modal, Form, Spin, Input, Select, Button, Table, Pagination, Switch, message } from 'antd';

import {
  PlusOutlined,
  SyncOutlined,
  CloseOutlined,
  CloseCircleOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import styles from './index.less';
import { connect } from 'dva';
const { Option } = Select;
const { Search } = Input;

import defaultSettings from '../../../../config/defaultSettings'

@Form.create()
@connect(({ system }) => ({ ...system }))
class RoleModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dateTime: '',
      checkColumns: [
        { title: '序号', width: 80, render: (text, record, index) => `${index + 1}` },
        { title: '角色名称', dataIndex: 'roleName', key: 'roleName' },
        {
          title: '状态',
          dataIndex: 'statusCd',
          key: 'statusCd',
          render: (text, record) => (
            <span style={{ color: text == 1 ? 'green' : 'red' }}>
              {text == 1 ? '启用' : '未启用'}
            </span>
          ),
        },
        {
          title: '操作',
          dataIndex: 'cz',
          width: 100,
          render: (text, record) => record.statusCd==1?<Button size="small" onClick={(checked)=>this.editUserFun(false,record)}>删除</Button>:<Button type="primary" size="small" onClick={(checked)=>this.editUserFun(true,record)}>启用</Button>
            // render: (text, record) => record.statusCd == 2?<Switch checked={false} onChange={()=>this.editUserFun(record,1)} />:
            // <a style={{ fontSize: '12px' }} onClick={() => this.editUserFun(record,2)}>
            //   <CloseOutlined />
            //   删除
            // </a>,
        },
      ],
      roleManList: [], //当前角色管理列表
      roleLoading: false,
      pageSize: 10,
      currentPage: 1,
      totalData: 1,
      selectedRowKeys: [],
      selectedRows: [],
      systemNameList: [],
      currSystemId: '',
      currRoleName: '',
      currStaffId: ''
    };
  }

  componentDidMount(){
    this.init()
  }

  init = ()=>{
    this.querySystemNameList()
  }

  querySystemNameList = async () => {
    const { props } = this;
    await props
      .dispatch({
        type: 'system/systemNameListPost',
        payload: {
          page: 1,
          rows: 20,
        },
      })
      .then(res => {
        if(res['list']){
          this.setState({
            systemNameList: res.list ? res.list : [],
            // currSystemId: res.list ? res.list[0].systemId : '',
            currSystemId: (defaultSettings.systemId&&defaultSettings.systemId!='')?defaultSettings.systemId: (res.list? res.list[0].systemId : '')
          });
          console.log(res, 'res');
        }else{
          message.error(res.msg)
        }
        
      });
  };

  componentWillReceiveProps(nextProps){
    const { userDetail,visible } = nextProps;
    if(visible){
      this.setState({
        currStaffId: userDetail.staffId
      },()=>{
        this.queryRoleManSever();
      })
    }
  }

  //获取当前角色管理列表
  queryRoleManSever = () => {
    this.setState({
      roleLoading: true,
    });
    const { props } = this;
    props
      .dispatch({
        type: 'system/queryRoleManList',
        payload: {
          dir: 'desc',
          page: this.state.currentPage,
          roleName: this.state.currRoleName,
          rows: this.state.pageSize,
          staffId:  this.state.currStaffId,
          systemId: this.state.currSystemId,
        },
      })
      .then(res => {
        this.setState({
          roleManList: res.list ? res.list : [],
          roleLoading: false,
          totalData: res.total,
        });
        console.log(res, 'res');
      });
  };

  editUserFun = (checked,record) => {
    const { props } = this;
    props
      .dispatch({
        type: record.relId==-1?'system/editAdminUserRolePost':'system/editUserRolePost',
        payload: {
          staffId: this.props.userDetail.staffId,
          relId: record.relId,
          roleId: record.roleId,
          statusCd: checked?1:2
        },
      })
      .then(res => {
        if(res.code == 0){
          this.setState({
            selectedRowKeys: []
          },()=>{
            this.queryRoleManSever()
          })
          message.success(checked?'启用成功！':'删除成功！')
        }else{
          message.error(checked?'启用失败！':'删除失败！')
        }
      });
  }

  handleCancel = e => {
    const { onCancel } = this.props;
    onCancel();
  };

  timeSelect = (value, dateString) => {
    this.setState({
      dateTime: dateString,
    });
  };

  //提交订单
  submitFun = value => {
    console.log(value, 'value');
    this.queryRoleManSever();
  };

  //重置
  resetFun = () => {
    this.setState(
      {
        currUsername: '',
        currOrgName: '',
        currTellphone: '',
        currStatus: '',
        currType: '',
        timestamp: Date.parse(new Date()) + 1,
      },
      () => {
        this.init();
      },
    );
  };

  //删除
  deleteData = record => {};

  onSelectChange = (selectedRowKeys,selectedRows) => {
    console.log(selectedRows, 'selectedRows');
    this.setState({ selectedRowKeys, selectedRows });
  };

  pageChange = page => {
    this.setState(
      {
        currentPage: page,
      },
      () => {
        this.queryRoleManSever();
      },
    );
  };

  systemChange = value => {
    this.setState({
      currSystemId: value
    });
  };

  roleNameChange = e => {
    this.setState({
      currRoleName: e.target.value
    });
  };

  batUserFun = (status) => {
    const { props, state: { selectedRows } } = this;
    let ampStaffRoleList = [];
    for(let i=0;i<selectedRows.length;i++){
      const item = {
        staffId: this.props.userDetail.staffId,
        relId: selectedRows[i].relId,
        roleId: selectedRows[i].roleId,
        statusCd: status
      }
      ampStaffRoleList.push(item)
    }
    props
      .dispatch({
        // type: selectedRows[0].relId==-1?'system/batAdminUserRolePost':'system/batUserRolePost',
        type: 'system/batAdminUserRolePost',
        payload: ampStaffRoleList,
      })
      .then(res => {
        if(res.code == 0){
          this.setState({
            selectedRowKeys: []
          },()=>{
            this.queryRoleManSever()
          })
          message.success(status==1?'启用成功！':'禁用成功！')
        }else{
          message.error(status==1?'启用失败！':'禁用失败！')
        }
      });
  }

  render() {
    const { form, loading , ...roleModalProps } = this.props;
    const { systemNameList, roleManList } = this.state;
    console.log( roleManList )
    // const { getFieldDecorator } = form;
    // const formItemLayout = {
    //     labelCol: {
    //       xs: { span: 24 },
    //       sm: { span: 8 },
    //     },
    //     wrapperCol: {
    //       xs: { span: 24 },
    //       sm: { span: 16 },
    //     },
    // };
    const { checkColumns, roleLoading, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    
    return (
      <Modal {...roleModalProps} onCancel={this.handleCancel} footer={null}>
        <Spin spinning={loading}>
          <dl>
            <dt>
              <Form name="horizontal_search" layout="inline">
                {
                  !defaultSettings.systemId||defaultSettings.systemId==''&&
                  <Form.Item name="status" label="系统名称">
                    <Select
                      style={{ width: 150 }}
                      placeholder="请选择系统名称"
                      onChange={this.systemChange}
                      value={this.state.currSystemId}
                    >
                      <Option value="">全部</Option>
                      {
                        systemNameList.map(item=>{
                          return(<Option value={item.systemId}>{item.systemName}</Option>)
                        })
                      }
                    </Select>
                  </Form.Item>
                }
                <Form.Item>
                  <Search
                    placeholder="请输入名称搜索"
                    style={{ width: 200 }}
                    onChange={this.roleNameChange}
                    onSearch={this.submitFun}
                    enterButton
                  />
                  <Button style={{ marginLeft: '8px' }} onClick={this.resetFun}>
                    <SyncOutlined />
                    重置
                  </Button>
                </Form.Item>
                <Form.Item style={{ float: 'right' }}>
                  <Button type="primary" style={{ marginRight: '5px' }} onClick={()=>this.batUserFun(1)} disabled={selectedRowKeys.length>0?false:true}>
                    <CheckCircleOutlined />
                    启用
                  </Button>
                  <Button onClick={()=>this.batUserFun(2)} disabled={selectedRowKeys.length>0?false:true}>
                    <CloseCircleOutlined />
                    禁用
                  </Button>
                </Form.Item>
              </Form>
            </dt>
            <dd>
              <Spin spinning={this.state.roleLoading} delay={500}>
                <Table
                  style={{ marginTop: '20px' }}
                  bordered
                  columns={checkColumns}
                  dataSource={roleManList}
                  // simple
                  // scroll={{ x: 1200 }}
                  pagination={false}
                  rowSelection={rowSelection}
                />
                {/* <Table rowSelection={rowSelection} columns={checkColumns} dataSource={roleManList} /> */}
              </Spin>
              <p style={{ textAlign: 'center', marginTop: '20px' }}>
                <Pagination
                  pageSize={this.state.pageSize}
                  current={this.state.currentPage}
                  total={this.state.totalData}
                  onChange={this.pageChange}
                />
              </p>
            </dd>
          </dl>
        </Spin>
      </Modal>
    );
  }
}

export default RoleModal;
